import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {DialogService} from "../../../service/dialogService";
import {CCRiskControllerService} from "../../../service/CCRiskController";
import {WeUIDatePicker, WeUIFile, WeUIPicker, WeUIToast, WeUIUploader} from "angular4-weui";
import {WeUIActionSheet} from "angular4-weui";
import {UIRiskReport} from "../../../entity/UIRiskReport";
import {RestRiskCommonType} from "../../../entity/RestRiskCommonType";
import {BaseAuthenticateComponent} from "../../../shared/component/baseAuthenticate.component";
import {RestRiskInfo} from "../../../entity/RestRiskInfo";
import {IMyDateModel, IMyDpOptions} from "mydatepicker";
import {UIRiskSubCategory} from "../../../entity/UIRiskSubCategory";
import {Observable} from "rxjs/Observable";
import {Subject} from "rxjs/Subject";
import {isSuccess} from "../../../shared/utils/RestRespTool";
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/concatMap';
import {IMAGE_PLAN_URL, IMAGE_HOSPITAL_URL} from "../../../constants"
import {JsSdkService} from "../../../service/jsSdkService";
import {UIRiskCategory} from "../../../entity/UIRiskCategory";
import {UIRiskCommonIssue} from "../../../entity/UIRiskCommonIssue";
import {UICCLocation} from "../../../entity/UICCLocation";
declare var wx: any;
@Component({
  selector: 'app-risk-report-detail',
  templateUrl: './risk-report-detail.component.html',
  styleUrls: ['./risk-report-detail.component.css']
})
export class RiskReportDetailComponent extends BaseAuthenticateComponent implements OnInit {

  reportId: number;
  reportInfo: UIRiskReport = new UIRiskReport();
  isUpdate = false;
  isModifiable = true;
  taskId: number;
  subCategoryId: number;
  comment: string;
  submitInfo: RestRiskInfo = new RestRiskInfo();
  request = '';

  options: RestRiskCommonType = new RestRiskCommonType();
  action: string;
  selectedDate: string;

  riskSubCategory : UIRiskSubCategory = new UIRiskSubCategory();
  checkFlag: any = {};
  type : string;
  private timer: any;

  IMAGE_PLAN_URL = IMAGE_PLAN_URL;
  IMAGE_HOSPITAL_URL = IMAGE_HOSPITAL_URL;

  uploadFiles = [];

  public myDatePickerOptions: IMyDpOptions = {
    // other options...
    dateFormat: 'yyyy/mm/dd',
  };

  riskImages = [];
  fixImages = [];
  lawList = [];
  tmpLawList = [];
  riskLevelList = [];
  riskTypeList = [];
  locationList = [];
  riskCauseList = [];

  error_info = '';
  code: string; // 二维码信息

  @ViewChild('actionsheet1') actionsheet1: WeUIActionSheet;
  @ViewChild('datePicker') datePicker: WeUIDatePicker;
  @ViewChild('successToast') successToast: WeUIToast;
  @ViewChild('uploader') uploader: WeUIUploader;
  @ViewChild('pickerLaw') pickerLaw: WeUIPicker;
  @ViewChild('pickerLevel') pickerLevel: WeUIPicker;
  @ViewChild('pickerType') pickerType: WeUIPicker;
  @ViewChild('pickerLocation') pickerLocation: WeUIPicker;
  @ViewChild('pickerCause') pickerCause: WeUIPicker;


  constructor(protected a_router: Router, public element: ElementRef, public _jsSdkService: JsSdkService,
              public route: ActivatedRoute, public _dialogService: DialogService, public riskService: CCRiskControllerService) {
    super(a_router, element, route);
    this.route.params.subscribe(params => {

      if (params['type']) { // expert已完成任务或admin任务-查看报告
        this.type = params['type'];
        this.isModifiable = false;
      }

      if (params['code']) { // 扫码后的信息
        this.code = params['code'];
      }

      if (params['executionId']) { // expert任务-创建或修改报告
        this.taskId = +params['executionId'];
        this.getLocationList();
      }

      if (params['subCategory']) {
        this.subCategoryId = +params['subCategory'];
        this.getRiskSubCategory();
      }

      if (params['reportId']) { // expert未完成任务-修改报告
        this.reportId = +params['reportId'];
        this.getRiskReportInfo();
        this.isUpdate = true;
      }
      if (params['action']) { // 发现隐患跳转到新建隐患报告页面，点击保存按钮 新建报告同时将流程从初查转换到初查完成
        this.action = params['action'];
      }
      if (params['location']) { // 发现隐患跳转到新建隐患报告页面
        this.reportInfo.location = params['location'];
      }
    });
  }

  ngOnInit() {
    this.getRiskCommonType();
    // this.configJSSDK();
    this.getLawLibaryList();
    this.getRiskCauseList();
  }

  // 获取法律法规列表
  getLawLibaryList() {
    this.riskService.lawLibraryList().subscribe(
      (lawLibraryList) => {
        if (lawLibraryList) {
          lawLibraryList.forEach((val, idx, array) => {
            this.lawList.push({label: val.name,
              value: val});
          });
        }
        // 添加空选项
        this.lawList.push({label: '无',
          value: null});
        this.tmpLawList = this.lawList;
        this.pickerLaw.menu = this.lawList;
      }
    );
  }

  // 获取隐患来源列表
  getRiskCauseList() {
    this.riskService.getRiskCause().subscribe(
      (riskCauseList) => {
        if (riskCauseList) {
          riskCauseList.forEach((val, idx, array) => {
            this.riskCauseList.push({label: val.name,
              value: val});
          });
        }
        // 添加空选项
        this.riskCauseList.push({label: '无',
          value: null});
        this.pickerCause.menu = this.riskCauseList;
      }
    );
  }

  getLocationList() {
    this.riskService.locationList(this.taskId).subscribe(
      (riskLocationList) => {
        if (riskLocationList) {
          riskLocationList.forEach((val, idx, array) => {
            let location = this.handleLocation(riskLocationList, val);
            // this.locationList.push({label: (val.parent == null ? '' : val.parent.name) + val.name,
            //   value: (val.parent == null ? '' : val.parent.name) + val.name});
            this.locationList.push({label: location,
              value: location});
          });
        }
        // 添加空选项
        this.locationList.push({label: '无',
          value: null});
        this.pickerLocation.menu = this.locationList;
      }
    );
  }

  handleLocation(locationList:UICCLocation[], location: UICCLocation) {
    if (location) {
      if (location.parent == null) {
        return location.name;
      } else {
        let parent = locationList.find((item) => item.id === location.parent.id);
        return this.handleLocation(locationList, parent) + location.name;
      }
    }
  }

  /**
   * 微信 JSSDK 配置
   */
  // configJSSDK() {
  //   this.url = location.href.split('#')[0];
  //   //由于Android和iOS微信签名时所用的url不同,区别对待
  //   if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {  //判断iPhone|iPad|iPod|iOS
  //     this.url = localStorage.getItem("initURL");
  //   }
  //   this._jsSdkService.getSignature(this.url).subscribe(
  //     (signature) => {
  //       this.appID = signature.appID;
  //       wx.config({
  //         debug: false,
  //         appId: signature.data.appid,
  //         timestamp: signature.data.timestamp,
  //         nonceStr: signature.data.nonceStr,
  //         signature: signature.data.signature,
  //         jsApiList: ['previewImage', 'chooseImage']
  //       });
  //     }
  //   );
  // }

  chooseImage() {
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        let localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
        alert('*** success ***' + JSON.stringify(localIds))
      }
    });
  }

  previewRiskImage(image) {
    wx.previewImage({
      current: image, // 当前显示图片的http链接
      urls: this.riskImages // 需要预览的图片http链接列表
    });
  }

  previewFixImage(image) {
    wx.previewImage({
      current: image, // 当前显示图片的http链接
      urls: this.fixImages // 需要预览的图片http链接列表
    });
  }

  getRiskReportInfo() {
    this.riskService.getRiskReportDetail(this.reportId).subscribe(
      (detail) => {
        this.reportInfo = detail;

        console.log('********** report info ********* ' + JSON.stringify(this.reportInfo))

        for (const indx in this.reportInfo.riskCommonIssue) {
          this.checkFlag[this.reportInfo.riskCommonIssue[indx].name] = true;
        }
        if (!this.type) {
          this.isModifiable = this.reportInfo.status !== 'finished'
        }
        // 处理隐患报告中的图片

        this.reportInfo.documentList.map(
          (document) => {
            this.riskImages.push(IMAGE_HOSPITAL_URL + document)
          }
        );
        if (this.reportInfo.riskSolution && this.reportInfo.riskSolution.photoIds) {
          this.reportInfo.riskSolution.photoIds.forEach(
            (photoId) => {
              this.fixImages.push(IMAGE_HOSPITAL_URL + photoId)
            }
          )
        };

      }
    );
  }

  getRiskSubCategory() {
    this.riskService.getSubCategory(this.subCategoryId).subscribe(
      (items) => {
        this.riskSubCategory = items;
      }
    );
  }

  getRiskCommonType() {
    this.riskService.getRiskCommonType().subscribe(
      (options) => {
        this.options = options;
        // this.options.riskLevel.forEach((val, idx, array) => {
        //   this.riskLevelList.push({label: val.name,
        //     value: val});
        // });
        // this.options.riskType.forEach((val, idx, array) => {
        //   this.riskTypeList.push({label: val.name,
        //     value: val});
        // });
        this.pickerLevel.menu = this.riskLevelList;
        this.pickerType.menu = this.riskTypeList;
      }
    );
  }

  validateReport() {
    let result = false;
    if (!this.reportInfo.location) {
      this.error_info = '请输入部门/部位';
    } else if (this.reportInfo.riskCommonIssue.length === 0) {
      this.error_info = '请至少选择一个隐患项';
    } else if (this.uploader.files.filter(item => item.isUploading).length > 0) {
      this.error_info = '正在上传图片不能保存并离开';
    } else {
      result = true;
    }

    return result;
  }
  saveReport() {
    if (this.validateReport()) {
      // 支持图片删除
      console.log('成功上传图片' + JSON.stringify(this.uploadFiles));
      console.log('图片上传选择器中图片' + JSON.stringify(this.uploader.files));

      const addedFiles = this.uploadFiles.filter(file => this.uploader.files.some((weuiFile) => file.fileURL === weuiFile.fileURL)); // 新添加的图片

      // 多个图片同时选择上传的时候 可以一张图片会上传两次 需要筛选成一次
      let uniqueFiles = []
      if (addedFiles) {
        addedFiles.forEach(
          (file) => {
            if (uniqueFiles.filter(file1 => file1.fileURL === file.fileURL).length === 0) {
              uniqueFiles.push(file)
            }
          }
        )
      }

      console.log('添加的图片' + JSON.stringify(uniqueFiles));

      if (uniqueFiles) {
        uniqueFiles.forEach(
          (file) => this.reportInfo.documentList.push(file.value)
        )
      }

      this.reportInfo.category = this.riskSubCategory.category
      this.reportInfo.subCategory = this.riskSubCategory
      this.reportInfo.request = this.request
      if (this.isUpdate === true) {
        this.riskService.updateRiskReport(this.reportInfo).subscribe(
          (res) => {
            this.navigatePage();
          }
        );
      } else {
        console.log('**** create ::: ' + JSON.stringify(this.reportInfo) + '  taskid :' + this.taskId)
        this.riskService.createRiskReportByTaskId(this.taskId, this.reportInfo).subscribe(
          (res) => {
            console.log('**** create success ::: ' + JSON.stringify(res));
            if (this.action === 'withrisk') {
              this.withRisk();
            } else {
              this.navigatePage();
            }
          }
        );
      }
    } else {
      this._dialogService.pushDialogMsg({showNOButton: false, title: "", content: this.error_info, btnOKText: "知道了"});
    }

  }

  withRisk() {
    this.submitInfo.comment = this.comment;
    this.riskService.withRisk(this.taskId, this.submitInfo).subscribe(
      () => {
        this.navigatePage();
        // this.a_router.navigate(["/dashboard/task"]);

      }
    );
  }

  navigatePage() {
    if (this.code) {
      this.a_router.navigate(["/dashboard/task", this.taskId, "detail", "scan", this.code]);
    } else {
      this.a_router.navigate(["/dashboard/task", this.taskId, "detail"]);
    }
    // this.successToast.show();
  }

  byId(item1: any, item2: any) {
    if (item1 && item2) {
      return item1.id === item2.id;
    }
    return false;
  }

  addCommonIssue(event, commonIssue: UIRiskCommonIssue) {
    if (event.target.checked) {
      // 隐患项可以多选(2018.11.05)
      // if (this.reportInfo.riskCommonIssue.length === 1) {
      //   this.checkFlag[commonIssue.name] = false;
      //   this._dialogService.pushDialogMsg({showNOButton: false, content: '只能选择一个隐患项', btnOKText: "知道了"});
      //   return;
      // }
      this.reportInfo.riskCommonIssue.push(commonIssue);
      this.checkFlag[commonIssue.name] = true;
      this.request = this.request + ' ' + commonIssue.request
    } else {
      this.reportInfo.riskCommonIssue = this.reportInfo.riskCommonIssue.filter((item) => item.id !== commonIssue.id);
      this.checkFlag[commonIssue.name] = false;
    }
  }

  onDateChanged1(event: IMyDateModel) {
    this.reportInfo.foundDate = event.jsdate;
  }

  onDateChanged2(event: IMyDateModel) {
    this.reportInfo.dueDate = event.jsdate;
  }

  showOptinos(): void {
    this.actionsheet1.show().then((menu: any) => {
      this.reportInfo.riskLevel = menu.text;
      console.log(JSON.stringify(this.reportInfo.riskLevel));
    });
  }

  showDatePicker(): void {
    this.selectedDate = '';
    this.datePicker.show().then((date: any) => {
      console.log('您刚刚选择了: ', JSON.stringify(date));
      for (let i = 0; i < date.length; i++) {
        // 此处必须用/不能用- safari浏览器不识别-连接的日期格式
        this.selectedDate += date[i].value.toString() + '/';
      }
      this.selectedDate = this.selectedDate.substring(0, this.selectedDate.length - 1);
      const foundDate = new Date(this.selectedDate);
      foundDate.setHours(foundDate.getHours() + 8);
      this.reportInfo.foundDate = foundDate;
    });
  }

  fileChange(event) {
    const files: WeUIFile[] = this.uploader.files;

    Observable.from(files)
      .filter((file: WeUIFile): boolean => !file.isUploaded)
      .concatMap((file: WeUIFile, index: number) => this.uploadFile(file, index))
      .subscribe((file: WeUIFile) => {
        if (file.hasError()) {
          console.log('文件“' + file.file.name + '”上传失败，原因：' + file.error);
        } else {
          console.log('文件“' + file.file.name + '”上传成功！');
        }
      }, (err: any) => {
        console.error(err);
      });
  }

  uploadFile(file: WeUIFile, index: number): Subject<WeUIFile> | ArrayLike<WeUIFile> {
    file.reset(); // 重置进度等
    file.isUploading = true;
    const subject = new Subject<WeUIFile>();
    console.log('file upload start ::: ' + file.file.name);
    this.timer = setInterval(() => {
      file.progress += 1;
    }, 1000);
    this.riskService.uploadFile(file.file).subscribe(
      res => {
        console.log('file upload ::: ' + JSON.stringify(res));
        if (isSuccess(res)) {
          clearInterval(this.timer);
          file.isUploading = false;
          file.isUploaded = true;
          file.progress = 100;
          this.uploadFiles.push({fileURL:file.fileURL, value:res.value})
          // this.reportInfo.documentList.push(res.value)
          subject.next(file);
          subject.complete();
        } else {
          clearInterval(this.timer);
          file.isUploading = false;
          file.isUploaded = false;
          file.error = '服务器错误';
          subject.next(file);
          subject.complete();
        }
      },
      err => {
        // this.handleError(err);
        clearInterval(this.timer);
        file.isUploading = false;
        file.isUploaded = false;
        file.error = '服务器错误';
        subject.next(file);
        subject.complete();
      }
    );

    return subject;
  }

  popRiskCause() {
    this.pickerCause.show().then((value: any) => {
      this.reportInfo.riskCause = value[0].value;
    });
  }

  popLaw() {
    // 法律法规可以多选
    this.pickerLaw.show().then((value: any) => {

      // 法律法规单选时
      // this.reportInfo.lawLibrary = value[0].value;

      this.reportInfo.lawLibraries.push(value[0].value);
      this.lawList = this.lawList.filter(item => item.label !== value[0].label);

      // 如果选择无 则清空
      if (value[0].label === '无') {
        this.reportInfo.lawLibraries = [];
        this.lawList = this.tmpLawList;
      }
      this.pickerLaw.menu = this.lawList;
    });
  }

  popLevel() {
    this.pickerLevel.show().then((value: any) => {
      this.reportInfo.riskLevel = value[0].value;
    });
  }

  popType() {
    this.pickerType.show().then((value: any) => {
      this.reportInfo.riskType = value[0].value;
    });
  }

  popLocations() {
    this.pickerLocation.show().then((value: any) => {
      this.reportInfo.location = value[0].value;
    });
  }

}
